package com.push.web.utils;

import com.push.common.utils.StringUtils;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OCRUtil {
  public static void main(String[] args) {
    String path = "D:/temp/upload/2022/07/20/df60998a-f0e3-4598-b8e8-45123d4764a1.tif";
      File file = new File(path);

      ITesseract instance = new Tesseract();
    instance.setDatapath("D:/temp/tessdata");
      //chi_sim ：简体中文， eng：英文    根据需求选择语言库
      instance.setLanguage("eng+chi_sim");

      String result = null;
      try {
          long startTime = System.currentTimeMillis();
          result =  instance.doOCR(file);
          long endTime = System.currentTimeMillis();
          if (StringUtils.isNotEmpty(result)){
              String[] res = result.split("\\r?\\n");
              List<String> stringA = Arrays.asList(res);
              String item = "";
              for (String a : stringA) {
                  a.replaceAll("|","");
                  if(startWithNumber(a)){
                      if (isContainChinese(item)){
                        System.out.println(item.replaceAll(" ", ""));
                      } else {
                          System.out.println(item);
                      }
                      item = a;
                  } else {
                      item += a;
                  }
              }
          }
          System.out.println("Time is：" + (endTime - startTime) + " 毫秒");
      } catch (TesseractException e) {
          e.printStackTrace();
      }

      //System.out.println("result: ");
      //System.out.println(result);
  }
    public static boolean startWithNumber(String str){
    return Pattern.matches("[0-9a-z].*", str);
    }
    /**
     * 字符串是否包含中文
     *
     * @param str 待校验字符串
     * @return true 包含中文字符 false 不包含中文字符
     */
    public static boolean isContainChinese(String str){
        Pattern p = Pattern.compile("[\u4E00-\u9FA5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
}
